import { DateFormat } from 'fdd-contract'
import formatDateString from '../../src/widgets/date-fill/formatDateString'

/** 获取图片地址 */
export function getImg(src: string) {
  // Vite 下获取静态资源地址
  return new URL(`../assets/img/${src}`, import.meta.url).href
}

/** svg 图片 base64 */
export function svg2Base64(svg: string) {
  return `data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(svg)))}`
}

/** 生成签署日期 base64 图片 */
export function createDateSign({
  date = new Date(),
  fontSize = 16,
  formate = DateFormat.LOCAL
}: {
  date?: Date
  fontSize?: number
  formate?: DateFormat
} = {}) {
  const format = (n: number) => (n < 10 ? `0${n}` : `${n}`)
  const [w, h] = [170, 28]
  const opacity = '0.8'
  const text = formatDateString(
    `${date.getFullYear()}/${format(date.getMonth() + 1)}/${format(date.getDate())}`,
    formate
  )

  return svg2Base64(`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${w}" height="${h}" viewbox="0 0 ${w} ${h}" fill-opacity="${opacity}" stroke-opacity="${opacity}">
      <text x="${w / 2}" y="${
    h / 2
  }" fill="black" font-family="宋体,SimSun" font-size="${fontSize}" style="text-anchor: middle; dominant-baseline: central;">${text}</text>
  </svg>`)
}

/** 生成签名 base64 图片 */
export function createSignature(text: string) {
  const [w, h] = [171, 92]
  const fontSize = 56
  const opacity = 0.8

  return svg2Base64(`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${w}" height="${h}" viewbox="0 0 ${w} ${h}" fill-opacity="${opacity}" stroke-opacity="${opacity}" >
      <text font-family="楷体,KaiTi" font-size="${fontSize}" x="${w / 2}" y="${
    h / 2
  }" fill="black" style="text-anchor: middle; dominant-baseline: central;">${text}</text>  
    <text x="130" y="86" fill="#888" font-size="12">E-Sign</text>
  </svg>`)
}
